<?php
/* SVN FILE: $Id: championships_controller.php 250 2010-06-17 10:55:41Z gregory.rome $ */
/**
 * Championships Controller.
 *
 * @todo Add file description.
 *
 * cBBweb : Digital Blood Bowl league interface (http://code.google.com/p/cbbweb/)
 * Copyright 2009-2010, Grégory Romé.
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2009-2010, Grégory Romé.
 * @link          http://code.google.com/p/cbbweb/ cBBweb Project
 * @package       cbbweb
 * @subpackage    cbbweb.controllers
 * @version       $Revision: 250 $
 * @modifiedby    $LastChangedBy: gregory.rome $
 * @lastmodified  $Date: 2010-06-17 10:55:41 +0000 (Thu, 17 Jun 2010) $
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */
/**
 * Championships Controller.
 *
 * @todo Add class description.
 *
 * @package       cbbweb
 * @subpackage    cbbweb.controllers
 */
class ChampionshipsController extends AppController {
	var $name = 'Championships';
	var $paginate = array (
		'Championship' => array (
			'contain' => array (
				'RuleType' => array (
					'LocalizedString'
				),
				'Team',
				'TeamRanking'
			)
		),
		'Team' => array (
			'contain' => array (
				'Coach',
				'Race' => array (
					'LocalizedString'
				),
				'StatisticsCurrentSeasonTeam'
			)
		)
	);

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function index() {
		$championships = $this->paginate('Championship');
		if (isset ($this->params['requested'])) {
			return $championships;
		} else {
			$this->set('championships', $championships);
		}
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Championship', true));
			$this->redirect(array (
				'action' => 'index'
			));
		}
		$this->Championship->recursive = 3;
		$championship = $this->Championship->read(null, $id);
		$this->set('championship', $championship);
		foreach ($championship['Team'] as $team) {
			$conditions[] = $team['ID'];
		}
		if (isset ($conditions)) {
			$teams = $this->paginate('Team', array (
				array ('Team.ID' => $conditions)
			));

			foreach ($teams as &$team) {
				$team['StatisticsTeam'] = $team['StatisticsCurrentSeasonTeam'];
				unset($team['StatisticsCurrentSeasonTeam']);
			}

			$this->set('teams', $teams);
		}
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function add() {
		if (!empty ($this->data['Championship'])) {
			$file = $this->data['Championship']['tmpFile'];
			if (!$this->isUploadedFile($file)) {
				$this->Session->setFlash(__('Upload failed', true));
			} else {
				rename($file['tmp_name'], '/tmp/last_tmp.sqlite');
				$ret = $this->_parseTempFile($this->data['Championship']);
				if ($ret) {
					$this->Session->setFlash(__('The Championship has been saved', true));
				} else {
					$this->Session->setFlash(__('The Championship could not be saved. Please, try again.', true));
				}
			}
		}
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function update() {
		if (!$this->championship) {
			$this->Session->setFlash(__('You must select a championship', true));
			$this->set('noview', true);
			return;
		} else {
			$this->set('noview', false);
			App :: import('Model', 'Championship');
			$Championship = new Championship();
			$championship = $Championship->read(null, $this->championship);
			$this->set('championship', $championship);
		}

		if (!empty ($this->data['Championship'])) {
			$file = $this->data['Championship']['tmpFile'];
			if (!$this->isUploadedFile($file)) {
				$this->Session->setFlash(__('Upload failed', true));
			} else {
				rename($file['tmp_name'], '/tmp/last_tmp.sqlite');

				$ret = $this->_parseTempFile($championship);
				if ($ret) {
					$this->Session->setFlash(__('The Championship has been saved', true));
				} else {
					$this->Session->setFlash(__('The Championship could not be saved. Please, try again.', true));
				}
			}
		}
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function _parseTempFile($currentChampionship)  {

		if( !isset($currentChampionship['Championship']['ID']) ) {
			$this->Championship->changeDataSource('temp');
			$this->Championship->recursive = -1;
			$championship = $this->Championship->find('first');
			$this->Championship->changeDataSource('default');
			$championship['Championship']['strName'] = $this->data['Championship']['strName'];
			unset ($championship['Championship']['ID']);
			$championship['Championship']['iSeason'] = 1;
			$ret = $this->Championship->save($championship);
			if(!$ret) { return $ret; }
			$championship['Championship']['ID'] = $this->Championship->getId();
		} else {
			$championship = $currentChampionship;
		}

		/* ------------------------------------------------------------------ */

		$this->Championship->Team->changeDataSource('temp');
		$this->Championship->Team->StatisticsTeam->changeDataSource('temp');
		$this->Championship->Team->Player->changeDataSource('temp');
		$this->Championship->Team->Player->StatisticsPlayer->changeDataSource('temp');
		$this->Championship->Team->Player->PlayerSkill->changeDataSource('temp');

		$teams = $this->Championship->Team->find('all', array(
			'contain' => array(
				'StatisticsTeam',
				'StatisticsSeasonTeam' => array(
					'conditions' => array('OR' => array(
						'StatisticsSeasonTeam.iSeason' => -1,
						'StatisticsSeasonTeam.bFinished' => 0))
				),
				'Player' => array(
					'StatisticsPlayer',
					'StatisticsSeasonPlayer' => array(
						'conditions' => array('OR' => array(
							'StatisticsSeasonPlayer.iSeason' => -1,
							'StatisticsSeasonPlayer.bFinished' => 0))
					),
					'PlayerSkill'
				)
			)
		));

		$this->Championship->Team->changeDataSource('default');
		$this->Championship->Team->StatisticsTeam->changeDataSource('default');
		$this->Championship->Team->Player->changeDataSource('default');
		$this->Championship->Team->Player->StatisticsPlayer->changeDataSource('default');
		$this->Championship->Team->Player->PlayerSkill->changeDataSource('default');

		foreach ($teams as &$team) {
			$result = $this->Championship->Team->find('first', array (
				'fields' => array ('Team.ID'),
				'conditions' => array ('Team.ID' => $team['Team']['ID']),
			));

			if (!$result) {
				$this->Championship->Team->create();

				unset($team['StatisticsTeam']['ID']);

				$team['StatisticsSeasonTeam'][0] = $team['StatisticsTeam'];
				$team['StatisticsSeasonTeam'][0]['iSeason'] = -1;
				$team['StatisticsSeasonTeam'][0]['bFinished'] = 1;
				unset($team['StatisticsSeasonTeam'][0]['ID']);

				$statisticsSeasonTeam = $team['StatisticsSeasonTeam'][0];
				$statisticsSeasonTeam['idRule_Listing'] = $championship['Championship']['ID'];
				$statisticsSeasonTeam['bFinished'] = 0;
				$statisticsSeasonTeam['iSeason'] = $championship['Championship']['iSeason'];

				unset($statisticsSeasonTeam['ID']);
				foreach ( $statisticsSeasonTeam as $key => $value ) {
					switch ( $key ) {
						case 'idTeam_Listing':
						case 'idRule_Listing':
						case 'iSeason':
						case 'bFinished':
							break;
						default:
							$statisticsSeasonTeam[$key] = 0;
							break;
					}
				}
				$team['StatisticsSeasonTeam'][1] = $statisticsSeasonTeam;

				foreach($team['Player'] as &$player) {
					unset($player['StatisticsPlayer']['ID']);
					foreach($player['PlayerSkill'] as &$playerSkill) {
						unset($playerSkill['ID']);
					}

					$this->Championship->Team->Player->StatisticsPlayer->create();
					$tmp['StatisticsPlayer'] = $player['StatisticsPlayer'];
					$this->Championship->Team->Player->StatisticsPlayer->save($tmp);
					unset($tmp);

					$tmp[0] = $player['StatisticsPlayer'];
					$tmp[0]['bFinished'] = 1;
					$tmp[0]['iSeason'] = -1;

					$tmp[1] = $player['StatisticsPlayer'];
					$tmp[1]['iSeason'] = $championship['Championship']['iSeason'];
					$tmp[1]['idRule_Listing'] = $championship['Championship']['ID'];
					$tmp[1]['bFinished'] = 0;

					foreach ( $tmp[1] as $key => $value ) {
						switch ( $key ) {
							case 'idPlayer_Listing':
							case 'idRule_Listing':
							case 'iSeason':
							case 'bFinished':
								break;
							default:
								$tmp[1][$key] = 0;
								break;
						}
					}
					$this->Championship->Team->Player->StatisticsSeasonPlayer->saveAll($tmp);

					$this->Championship->Team->Player->PlayerSkill->create();
					$this->Championship->Team->Player->PlayerSkill->saveAll($player['PlayerSkill']);
				}

			} else {

				$result = $this->Championship->Team->StatisticsTeam->find('first', array(
					'fields' => array('StatisticsTeam.ID'),
					'conditions' => array('StatisticsTeam.idTeam_Listing' => $team['Team']['ID']),
				));
				if(!$result) {
					unset($team['StatisticsTeam']['ID']);
				} else {
					$team['StatisticsTeam']['ID'] = $result['StatisticsTeam']['ID'];
					unset($result);
				}

				/* FIXME: the table need a new field to store the championship */
				foreach($team['StatisticsSeasonTeam'] as &$statisticsSeasonTeam) {
					$result = $this->Championship->Team->StatisticsSeasonTeam->find('first', array(
						'fields' => array('StatisticsSeasonTeam.ID'),
						'conditions' => array(
							'StatisticsSeasonTeam.idTeam_Listing' => $team['Team']['ID'],
							'StatisticsSeasonTeam.iSeason' => $team['StatisticsSeasonTeam']['iSeason']
						),
					));

					if(!$result) {
						unset($statisticsSeasonTeam['ID']);
					} else {
						$statisticsSeasonTeam['ID'] = $result['StatisticsSeasonTeam']['ID'];
						unset($result);
					}
				}

				/* ------------------------------------------------------------------ */

				foreach($team['Player'] as &$player) {

					$result = $this->Championship->Team->Player->StatisticsPlayer->find('first', array(
						'fields' => array('StatisticsPlayer.ID'),
						'conditions' => array('StatisticsPlayer.idPlayer_Listing' => $player['ID']),
					));
					if(!$result) {
						unset($player['StatisticsPlayer']['ID']);
					} else {
						$player['StatisticsPlayer']['ID'] = $result['StatisticsPlayer']['ID'];
						unset($result);
					}

					foreach($player['PlayerSkill'] as &$playerSkill) {
						$result = $this->Championship->Team->Player->PlayerSkill->find('first', array(
							'fields' => array('PlayerSkill.ID'),
							'conditions' => array(
								'PlayerSkill.idPlayer_Listing' => $player['ID'],
								'PlayerSkill.idSkill_Listing' => $playerSkill['idSkill_Listing'],
							),
						));
						if(!$result) {
							unset($playerSkill['ID']);
						} else {
							$playerSkill['ID'] = $result['PlayerSkill']['ID'];
							unset($result);
						}
					}
				}
			}
			$ret = $this->Championship->Team->saveAll($team);
			$championship['Team'][] = $team['Team']['ID'];
		}

		/* ------------------------------------------------------------------ */
		/* Save the calendars */

		$this->Championship->Calendar->changeDataSource('temp');
		$this->Championship->Calendar->recursive = -1;
		$calendars = $this->Championship->Calendar->find('all');
		$this->Championship->Calendar->changeDataSource('default');

		foreach ($calendars as $calendar) {
			unset ($calendar['Calendar']['ID']);
			$this->Championship->Calendar->create();
			$ret = $this->Championship->Calendar->save($calendar);
			$championship['Calendar'][] = $this->Championship->Calendar->getId();
		}

		/* ------------------------------------------------------------------ */
		/* Save the championship */

		$ret = $this->Championship->save($championship);
		if ($ret) {
			$this->Session->setFlash(__('The Championship has been saved', true));
			$this->redirect(array (
				'action' => 'view',
				'id' => $this->Championship->getId()
			));
		} else {
			$this->Session->setFlash(__('The Championship could not be saved. Please, try again.', true));
		}

	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function edit($id = null) {

		if (!$id && empty ($this->data)) {
			$this->Session->setFlash(__('Invalid Championship', true));
			$this->redirect(array (
				'action' => 'index'
			));
		}

		if (!empty ($this->data)) {
			if ($this->Championship->save($this->data)) {
				$this->Session->setFlash(__('The Championship has been saved', true));
				$this->redirect(array ('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The Championship could not be saved. Please, try again.', true));
			}
		}
		if (empty ($this->data)) {
			$this->data = $this->Championship->read(null, $id);
		}
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function delete($id = null) {

		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Championship', true));
			$this->redirect(array ('action' => 'index'));
		}

		if ($this->Championship->del($id)) {
			$this->Session->setFlash(__('Championship deleted', true));
			$this->redirect(array ('action' => 'index'));
		}

		$this->Session->setFlash(__('The Championship could not be deleted. Please, try again.', true));
		$this->redirect(array ('action' => 'index'));
	}

}
?>